<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <TaskTitle :title-name="titleName" icon-name="to do" color="blue" />
    <div class="g-drawer-list-container">
      <div class="g-drawer-progress-container">
        <TitleSecondary title="审批流程图" />
        <ProgressStaus />
      </div>
      <ProgressTransverse
        :node-list="detail.nodeList"
        :name-list="detail.nameList"
      />
      <TitleSecondary title="基本信息" />
      <FormBasicInfoList :form="form" :plan-type="planType" />
      <TitleSecondary title="销售责任人" />
      <TableSaleList
        :data-source="detail.planSales"
        style="margin-bottom: 20px"
      />
      <TitleSecondary :title="`${PLAN_TYPE[planType]}计划明细`" />
      <TablePlanDetail
        ref="table-detail"
        :data-source="planDetailList"
        :is-edit="false"
        :hide-keys="hasEdit ? [] : ['selection']"
        :plan-sales="detail.planSales"
        :plan-type="planType"
        :plan-sales-id="detail.planSalesId"
        :plan-id="planId"
        :local-key="`${PLAN_TYPE[planType]}-saler-audit`"
        :buttons="[
          {
            key: 'show',
            label: '显示字段',
          },
          {
            key: 'screenfull',
            label: '全屏显示',
          },
        ]"
        :time-range="[form.startTime, form.endTime]"
        :parent-id="form.salesOrganization"
        @checked="handleTableCheckedChange"
      />
      <TitleSecondary v-if="hasEdit" title="审批信息" />
      <ApprovalInformation
        v-if="hasEdit"
        ref="approval"
        :disabled-agree="disabledAgree"
        :disabled-refuse="disabledRefuse"
      />
      <TitleSecondary
        title="操作日志"
        :icon="iconStaus"
        @change="handleChangeIcon"
      />
      <ProgressPortrait
        v-show="isShowProgressPortrait"
        :operation-log="operationLogInformation"
      />
      <BottomLine />
    </div>
    <ButtonGroup
      class="g-drawer-footer"
      :options="filterButtons"
      @click="handleButtonClick"
    />
    <DialogTransfer
      :visible.sync="visibleTransfer"
      :plan-id="planId"
      @change="onClose"
    />
  </p-drawer>
</template>

<script>
import FormBasicInfoList from '@/components/task/FormBasicInfoList.vue';
import TableSaleList from '@/components/task/TableSaleList.vue';
import ProgressTransverse from '@/components/task/ProgressTransverse.vue';
import ProgressPortrait from '@/components/task/ProgressPortrait.vue';
import ProgressStaus from '@/components/task/ProgressStaus.vue';
import TablePlanDetail from '@/components/task/TablePlanDetail.vue';
import ApprovalInformation from '@/components/task/ApprovalInformation.vue';
import DialogTransfer from '@/components/dialog/DialogTransfer.vue';

import { getOperationLog, postSaleDirectorApprove } from '@/api/plan';
import DrawerMixin from './mixin';

export default {
  components: {
    FormBasicInfoList,
    TablePlanDetail,
    TableSaleList,
    ProgressTransverse,
    ProgressPortrait,
    ProgressStaus,
    ApprovalInformation,
    DialogTransfer,
  },
  mixins: [DrawerMixin],

  props: {},
  data() {
    return {
      operationLogInformation: [], //操作日志请求返回的信息
      iconStaus: 'down', //icon图片up、down的切换
      planDetailList: [],
      visibleTransfer: false,
      checkedGroups: {},
      groups: {},
    };
  },
  computed: {
    disabledAgree() {
      const checkedLength = Object.keys(this.checkedGroups).filter(
        (el) => this.checkedGroups[el]
      ).length;
      const groupsLenght = Object.keys(this.groups).length;
      if (checkedLength === 0) return true;
      return checkedLength !== groupsLenght;
    },
    disabledRefuse() {
      const checkedLength = Object.keys(this.checkedGroups).filter(
        (el) => this.checkedGroups[el]
      ).length;
      return checkedLength < 1;
    },
    isShowProgressPortrait() {
      return this.iconStaus === 'up';
    },
    form() {
      return this.detail.plan || {};
    },
    footerButtons() {
      return [
        {
          key: 'submit',
          type: 'primary',
          label: '提交',
          auth: true,
        },
        {
          key: 'transfer',
          label: '转他人处理',
          auth: true,
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },
  methods: {
    handleTableCheckedChange(checkedGroups, groups) {
      this.checkedGroups = checkedGroups;
      this.groups = groups;
    },
    async handleChangeIcon(icon) {
      this.iconStaus = icon === 'down' ? 'up' : 'down';
      if (this.operationLogInformation.length === 0) {
        let res = await getOperationLog({
          planNumber: this.planId,
        });
        this.operationLogInformation = res.data.data;
      }
    },
    onClose() {
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },
    closeCallback() {
      this.onClose();
    },
    async submitCallback() {
      const data = this.$refs.approval?.form || {};
      if (typeof data.approveStatus !== 'boolean') {
        this.$message.error('请先进行审批！');
        return;
      }
      if (data.approveStatus === false && !data.approveOpinion) {
        this.$message.error('请填写审批意见！');
        return;
      }
      if (data.approveStatus === true && this.disabledAgree) {
        this.$message.error('明细表未选择全部！');
        return;
      }
      if (data.approveStatus === false && this.disabledRefuse) {
        this.$message.error('请至少选择一条数据');
        return;
      }
      const checkedGroupsIds = Object.keys(this.checkedGroups).reduce(
        (pre, cur) => {
          if (this.checkedGroups[cur]) {
            pre.push(cur);
          }
          return pre;
        },
        []
      );
      const rejectList = data.approveStatus ? undefined : checkedGroupsIds;
      await postSaleDirectorApprove({
        ...data,
        planId: this.planId,
        rejectList,
      });
      this.$message.success('提交成功！');
      this.closeCallback();
    },
    transferCallback() {
      this.visibleTransfer = true;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
  },
};
</script>

